package com.sdkj.dspservice.modules.demand.timer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdkj.dspservice.common.utils.CollectionsUtils;
import com.sdkj.dspservice.common.utils.DateUtils;
import com.sdkj.dspservice.common.utils.dsp.CdpUtils;
import com.sdkj.dspservice.modules.demand.entity.Demand;
import com.sdkj.dspservice.modules.demand.entity.DemandDetails;
import com.sdkj.dspservice.modules.demand.service.DemandDetailsService;
import com.sdkj.dspservice.modules.demand.service.DemandService;
import com.sdkj.dspservice.modules.sys.entity.User;
import com.sdkj.dspservice.modules.sys.service.UserService;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * 需求模块定时器任务
 */
@Configuration
@EnableScheduling   // 2.开启定时任务
@RestController
@RequestMapping(value = "demandTimer")
public class DemandTimer {

    @Autowired
    private DemandService demandService;
    @Autowired
    private DemandDetailsService demandDetailsService;
    @Autowired
    private UserService userService;

    static DefaultWebSecurityManager manager = new DefaultWebSecurityManager();

    /**
     * 每天服务器的1点和10点（中国时间9点和18点），自动确认，已处理超过72小时的需求
     * @throws SQLException
     * @throws InterruptedException
     */
    @Scheduled(cron = "0 0 1,10 * * ?")
    private void autoConfirm() {
//    @RequestMapping(value = "autoConfirm")
//    public void autoConfirm() {
        ThreadContext.bind(manager);
        // 获取所有已处理中，没有结束时间的需求
        QueryWrapper<DemandDetails> demandDetailsQw = new QueryWrapper<>();
        demandDetailsQw.eq("demand_status", Demand.STATUS_PROCESSED);
        demandDetailsQw.eq("demand_flow_status", Demand.FLOW_STATUS_WAIT_FINISH);
        demandDetailsQw.isNull("end_date");
        List<DemandDetails> demandDetailsList = demandDetailsService.list(demandDetailsQw);
        if (CollectionsUtils.isNotEmpty(demandDetailsList)) {
            for (DemandDetails demandDetails : demandDetailsList) {
                // 查询上一个流程
                QueryWrapper<DemandDetails> lastQw = new QueryWrapper<>();
                lastQw.eq("demand_id", demandDetails.getDemandId());
                lastQw.eq("flow_sort", demandDetails.getFlowSort() - 1);
                List<DemandDetails> ddList = demandDetailsService.list(lastQw);
                if(CollectionsUtils.isNotEmpty(ddList)){
                    DemandDetails prevDemandDetails = ddList.get(0);
                    // 获取处理完成时间到现在的小时数
                    long hour = DateUtils.pastHour(prevDemandDetails.getEndDate(), new Date());
                    // 如果hour>=72，则该条需求需要自动完成
                    if(hour >= 72){
                        Demand demand = new Demand(demandDetails.getDemandId());
                        demandDetails.setId(null);
                        demandDetails.setDemand(demand);
                        demandDetails.setDescription("处理人提交后，72小时自动确认");
                        demandDetails.setMakeType(DemandDetails.MAKE_TYPE_FINISH);
                        demandService.flow(demandDetails);
                    }
                }
            }
        }
    }

    /**
     * 每天服务器的1点和10点（中国时间9点和18点），自动关闭
     * 查询未经过处理人且已退回的需求，每超过24小时，发送一条提醒短信，超过72小时后自动关闭
     * @throws SQLException
     * @throws InterruptedException
     */
    @Scheduled(cron = "0 0 1,10 * * ?")
    private void autoClose() {
//    @RequestMapping(value = "autoClose")
//    public void autoClose() {
        ThreadContext.bind(manager);
        // 获取所有退回状态的需求
        QueryWrapper<Demand> demandQueryWrapper = new QueryWrapper<>();
        demandQueryWrapper.eq("status", Demand.STATUS_REJECT);
        List<Demand> demandList = demandService.list(demandQueryWrapper);
        if (CollectionsUtils.isNotEmpty(demandList)) {
            for (Demand demand : demandList) {
                // 判定该需求未经过“需求处理人”：在该需求详情中，不存在流程状态为“待处理”的数据
                QueryWrapper<DemandDetails> demandDetailsQueryWrapper = new QueryWrapper<>();
                demandDetailsQueryWrapper.eq("demand_id", demand.getId());
                demandDetailsQueryWrapper.eq("demand_flow_status", Demand.FLOW_STATUS_PROCESS);
                List<DemandDetails> demandDetailsList = demandDetailsService.list(demandDetailsQueryWrapper);
                if(demandDetailsList.isEmpty()){
                    // 为空说明条件满足，接下来判断时间，发送短信，demand的updateDate，即为退回时间，create_by即为需求发起人
                    // 获取退回时间到现在的小时数
                    long hour = DateUtils.pastHour(demand.getUpdateDate(), new Date());
                    // 获取用户详细信息
                    User user = userService.getById(demand.getCreateBy());
                    if(hour >= 24 && hour <= 48){
                        CdpUtils.sendMobileMessage(user.getMobile(), "您的需求《" + demand.getName() + "》已退回超过24小时未处理，请及时处理。若72小时内未处理，该需求将被关闭。");
                    }else if(hour > 72){
                        CdpUtils.sendMobileMessage(user.getMobile(), "您的需求《" + demand.getName() + "》已退回超过72小时未处理，该需求已关闭");
                        // 关闭该需求
                        Demand demandSave = new Demand(demand.getId());
                        DemandDetails demandDetails = new DemandDetails();
                        demandDetails.setId(null);
                        demandDetails.setDemand(demandSave);
                        demandDetails.setDescription("已退回超过72小时未处理，该需求已关闭");
                        demandDetails.setMakeType(DemandDetails.MAKE_TYPE_ClOSE);
                        demandService.flow(demandDetails);
                    }
                }
            }
        }
    }

}